﻿using Microsoft.Owin.Cors;
using Owin;
using Serilog;
using Sustainalytics.RiskRatings.Service.Infrastructure;
using Sustainalytics.Utils;
using System.Configuration.Abstractions;
using System.Threading.Tasks;
using System.Web.Cors;
using System.Web.Http;
using System.Web.Http.Dispatcher;

namespace Sustainalytics.RiskRatings.Service
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            if (ConfigurationManager.Instance.AppSettings.AppSettingSilent("enableCors", () => false))
                app.UseCors(CorsOptions.AllowAll);

            RegisterSerilog();

            app.Use<OwinExceptionMiddleware>();

            #region CORS policy
            if (ConfigurationManager.Instance.AppSettings.AppSettingSilent("ClientUrlOnly", () => true))
            {
                var policy = new CorsPolicy()
                {
                    AllowAnyOrigin = false,
                    AllowAnyHeader = true,
                    AllowAnyMethod = true,
                    SupportsCredentials = true
                };

                policy.Origins.Add(ConfigurationManager.Instance.AppSettings.AppSettingSilent("ClientUrl", () => "*"));

                app.UseCors(new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context => Task.FromResult(policy)
                    }
                });
            }
            #endregion

            app.UseAuthenticationServer();       
            app.Use<OwinAuthorizationMiddleware>();

            var config = new HttpConfiguration();
            config.Filters.Add(new LogControllerFilter(true, true, false));

            var container = CompositionRoot.RegisterDependencies(config);


            config.Services.Replace(typeof(IHttpControllerActivator), new SimpleInjectorControllerActivator(container));

            WebApiConfig.Register(config);

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            app.UseWebApi(config);

            config.EnsureInitialized();
        }

        public static void RegisterSerilog()
        {
            Log.Logger = new LoggerConfiguration()
                .Enrich.WithProcessName()
                .Enrich.WithMachineName()
                .Enrich.FromLogContext()
                .ReadFrom.AppSettings()
                .CreateLogger();
        }
    }
}
